<template>
  <div class="app-container-custom">
    <el-row :gutter="10">
      <el-col :span="5" :xs="24">
        <el-card shadow="never">
          <org-tree ref="orgTree" modelType="'dept'" @nodeClick="handleNodeClick"
                    @firstNodeClick="handleFirstNodeClick"/>
        </el-card>
      </el-col>
      <el-col :span="19" :xs="24">
        <el-card shadow="never">
          <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="小区编号" prop="communityNum">
              <el-input
                v-model="queryParams.communityNum"
                placeholder="请输入小区编号"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="小区名称" prop="communityName">
              <el-input
                v-model="queryParams.communityName"
                placeholder="请输入小区名称"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['property:community:add']"
              >新增
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['property:community:edit']"
              >修改
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['property:community:remove']"
              >删除
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                :loading="exportLoading"
                @click="handleExport"
                v-hasPermi="['property:community:export']"
              >导出
              </el-button>
            </el-col>
            <el-col :span="1.5">

            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <el-table v-loading="loading" :data="communityList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="小区编号" align="center" prop="communityNum" width="120"/>
            <el-table-column label="小区名称" align="center" prop="communityName" width="120"/>
            <el-table-column label="小区城市" width="180" show-overflow-tooltip align="center" prop="cityName"/>
            <el-table-column label="小区地址" width="180" show-overflow-tooltip align="center" prop="address"/>
            <el-table-column label="所属机构" align="center" prop="deptName" width="180"/>
            <el-table-column label="小区面积" align="center" prop="communityArea" width="120"/>
            <el-table-column label="当前账期" align="center" prop="fiscalPeriod" width="120"/>
            <!--<el-table-column label="会计年度" align="center" prop="fiscalPeriod.fiscalYear" width="120"/>-->
            <!--<el-table-column label="会计期间" align="center" prop="fiscalPeriod.period" width="120"/>-->
            <!--<el-table-column label="会计期间开始时间" align="center" prop="fiscalPeriod.periodBeginTime" width="180"/>-->
            <!--<el-table-column label="会计期间结束时间" align="center" prop="fiscalPeriod.periodFinishTime" width="180"/>-->
            <!-- <el-table-column label="数据状态" align="center" prop="statusCd" :formatter="statusCdFormat" />-->
            <el-table-column label="操作" align="center" width="150" fixed="right" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <!--<el-button-->
                <!--size="mini"-->
                <!--type="text"-->
                <!--icon="el-icon-edit"-->
                <!--v-if="!scope.row.fiscalPeriodId"-->
                <!--@click="handleFiscalPeriod(scope.row)"-->
                <!--&gt;设置会计期间</el-button>-->

                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  v-if="!scope.row.fiscalPeriod"
                  @click="initFiscalPeriod(scope.row)"
                  v-hasPermi="['property:community:fiscalPeriod']"
                >初始化当前账期
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改小区信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body v-drag-fullscreen>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="小区编号" prop="communityNum">
          <el-input v-model="form.communityNum" placeholder="请输入小区编号"/>
        </el-form-item>
        <el-form-item label="小区名称" prop="communityName">
          <el-input v-model="form.communityName" placeholder="请输入小区名称"/>
        </el-form-item>
        <el-form-item label="小区城市" prop="cityCode">
          <el-cascader
            v-model="selectedAddress"
            ref="myCascader"
            placeholder="试试搜索：河南"
            :options="options"
            @change="changeSelect"
            filterable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="小区面积" prop="communityArea">
          <el-input v-model="form.communityArea" placeholder="请输入小区面积"/>
        </el-form-item>
        <el-form-item label="所属机构" prop="deptId">
          <treeselect
            v-model="form.deptId"
            :options="deptOptions"
            :normalizer="normalizer"
            placeholder="选择所属机构"
            @select="selectDepart"
          />
        </el-form-item>
        <el-form-item label="小区地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--<fit-fiscal-period ref="periodRef" />-->
    <init-fiscal-period ref="initFiscalRef" @ok="getList"/>
  </div>
</template>

<script>
  import {
    listCommunity,
    getCommunity,
    delCommunity,
    addCommunity,
    updateCommunity,
    exportCommunity
  } from "@/api/property/community";
  import {listDept} from "@/api/system/dept";
  import {treeData} from "@/api/system/category";
  // import FitFiscalPeriod from "./FitFiscalPeriod";
  import InitFiscalPeriod from "./initFiscalPeriod";

  export default {
    name: "Community",
    components: {InitFiscalPeriod},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 小区信息表格数据
        communityList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 数据状态字典
        statusCdOptions: [],
        selectedAddress: [],
        deptOptions: [],
        options: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          deptId: null,
          communityNum: null,
          communityName: null,
          address: null,
          cityName: null,
          cityCode: null,
          communityArea: null,
          ancestors: null,
          latitude: null,
          longitude: null,
          position: null,
          dataSourceId: null,
          state: null,
          statusCd: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          cityCode: [
            {required: true, message: "小区城市不能为空", trigger: "blur"},
          ],
          communityArea: [
            {required: true, message: "小区面积不能为空", trigger: "blur"},
          ],
          communityNum: [
            {required: true, message: "小区编号不能为空", trigger: "blur"},
          ],
          communityName: [
            {required: true, message: "小区名称不能为空", trigger: "blur"},
          ],
          deptId: [
            {required: true, message: "物业单位不能为空", trigger: "blur"},
          ],
        }
      };
    },
    created() {
      this.getList();
      this.getCategoryList();
      this.getDicts("sys_normal_disable").then(response => {
        this.statusCdOptions = response.data;
      });
    },
    methods: {
      /** 查询小区信息列表 */
      getList() {
        this.loading = true;
        listCommunity(this.queryParams).then(response => {
          this.communityList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      getDeptList() {
        listDept().then(response => {
          this.deptOptions = this.handleTree(response.data, "deptId");
        });
      },
      // 数据状态字典翻译
      statusCdFormat(row, column) {
        return this.selectDictLabel(this.statusCdOptions, row.statusCd);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          deptId: null,
          communityNum: null,
          communityName: null,
          address: null,
          cityName: null,
          cityCode: null,
          communityArea: null,
          ancestors: null,
          latitude: null,
          longitude: null,
          position: null,
          dataSourceId: null,
          state: null,
          statusCd: "0",
          createBy: null,
          createByCode: null,
          createTime: null,
          updateBy: null,
          updateByCode: null,
          updateTime: null,
          remark: null,
          fiscalPeriod: null
        };


        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加小区信息";
        this.getDeptList();
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.getDeptList();
        const id = row.id || this.ids
        getCommunity(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改小区信息";
          if (this.form.cityCode && this.form.cityCode.length > 0) {
            this.selectedAddress = this.form.cityCode.split(',');
          }
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateCommunity(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addCommunity(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      changeSelect(node) {
        let nodes = this.getCascaderObj(node, this.options);
        this.form.cityName = this.jointSrc(nodes, 'label', "/");
        this.form.cityCode = this.jointSrc(nodes, 'value', ",");
      },
      getCascaderObj(val, opt) {
        return val.map(function (value, index, array) {
          for (var itm of opt) {
            if (itm.value == value) {
              opt = itm.children;
              return itm;
            }
          }
          return null;
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除小区信息编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delCommunity(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有小区信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportCommunity(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {
        });
      },
      /** 转换部门数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.deptId,
          label: node.deptName,
          children: node.children
        };
      },
      selectDepart(node, instanceId) {
        this.form.ancestors = node.ancestors + "," + node.deptId;
        this.form.deptName = node.deptName;
      },
      /** 查询分类字典列表 */
      getCategoryList() {
        treeData({}, '10001').then(response => {
          this.options = response.data;
          this.deleteLastNode(this.options);
        });
      },
      deleteLastNode(rows) {
        for (var i in rows) {
          let row = rows[i];
          if (row.children.length > 0) {
            this.deleteLastNode(row.children);
          } else {
            delete row['children'];
          }
        }
      },
      handleNodeClick(node) {
        this.queryParams.nodeId = node.id
        this.getList()
      },
      handleFiscalPeriod(row) {
        this.$refs.periodRef.show(row)
      },
      handleFirstNodeClick(node) {
        this.currentNode = node;
        this.queryParams.nodeId = node.id;
        this.getList();
      },
      initFiscalPeriod(row) {
        this.$refs.initFiscalRef.show({form: {id: row.id, fiscalPeriod: row.fiscalPeriod}})
      }
    }
  };
</script>
<style lang="scss">
  .el-cascader-menu {
    height: 300px;
  }
</style>
